package com.ledim.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.ledim.app.LeDimApplication;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.bean.LoginResponseBean;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.service.coverter.LedimGsonConverterFactory;
import com.letv.android.young.client.R;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.service.LedimHttpObserver;
import com.ledim.ledimview.OtherLoginView;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LedimNetWorkUtils;
import com.ledim.utils.ToastUtil;
import com.ledim.widget.view.LoadingBar;
import java.util.HashMap;
import org.greenrobot.eventbus.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 用户登录
 */
public class UserLoginActivity extends LeDimBaseActivity
        implements View.OnClickListener, View.OnTouchListener {

    public static final String NEED_LOGIN = "needLogin";
    private ImageView mBack;
    private TextView mForget;
    private TextView mTitle;
    private TextView mRight;

    private Button mLogin;
    private View mBigBgLayout;
    private EditText mAccount;
    private EditText mPassword;
    private String mAccountStr;
    private String mPasswordStr;
    private OtherLoginView mOtherLoginView;
    private boolean mNeedLogin;
    private LoadingBar mLoading;

    private static final int REGISTER_REQUEST_CODE = 0x18;
    public static final int REGISTER_RESPONSE_CODE = 0x19;
    public Bundle mBundle;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_user_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        mNeedLogin = getIntent().getBooleanExtra(NEED_LOGIN, false);
    }

    @Override
    protected void initIntentData(Bundle bundle) {
        super.initIntentData(bundle);
        mBundle = bundle;
    }

    private void initView() {
        mBack = (ImageView) findViewById(R.id.user_top_view_back);
        mTitle = (TextView) findViewById(R.id.user_top_view_title);
        mRight = (TextView) findViewById(R.id.user_top_view_right);
        mBigBgLayout = findViewById(R.id.user_login_big_layout);
        mLogin = (Button) findViewById(R.id.user_login_btn);
        mForget = (TextView) findViewById(R.id.user_login_forget);
        mAccount = (EditText) findViewById(R.id.user_login_username);
        mPassword = (EditText) findViewById(R.id.user_login_password);
        mOtherLoginView = (OtherLoginView) findViewById(R.id.other_login_view);

        mRight.setVisibility(View.VISIBLE);
        mRight.setText("注册");

        mBack.setOnClickListener(this);
        mRight.setOnClickListener(this);
        mLogin.setOnClickListener(this);
        mForget.setOnClickListener(this);
        mBigBgLayout.setOnTouchListener(this);

        mTitle.setText("登录");
        mTitle.setVisibility(View.VISIBLE);
        mOtherLoginView.bindData(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mOtherLoginView.WeixinhandleIntent(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mOtherLoginView.activityResult(requestCode, resultCode, data);
        if (resultCode == REGISTER_RESPONSE_CODE) {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.user_top_view_back:
                finish();
                break;
            case R.id.user_top_view_right:
                goToOthersForResult(UserRegisterActivity.class, null, REGISTER_REQUEST_CODE);
                break;
            case R.id.user_login_btn:
                if (LedimNetWorkUtils.isNetworkAvailable(this)) {
                    verifyContent();
                } else {
                    ToastUtil.toast(R.string.net_error);
                }
                break;
            case R.id.user_login_forget:
                intent = new Intent(this, UserFindPasswordActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void verifyContent() {
        mAccountStr = mAccount.getText().toString().trim();
        mPasswordStr = mPassword.getText().toString().trim();
        if (mAccountStr == null || mAccountStr.length() == 0) {
            ToastUtil.toast("请输入账号");
            mAccount.requestFocus();
        } else if (mPasswordStr == null || mPasswordStr.length() == 0) {
            ToastUtil.toast("请输入密码");
            mPassword.requestFocus();
        } else if (mPasswordStr.matches("^[\\u4e00-\\u9fa5]+$")) {
            ToastUtil.toast("密码是6-16位的数字/字母/符号");
            mPassword.requestFocus();
        } else if (mPasswordStr.length() < 6 || mPasswordStr.length() > 16) {
            ToastUtil.toast("密码是6-16位的数字/字母/符号");
            mPassword.requestFocus();
        } else {
            //mLoginModel.login();
            //登录
            if (mLoading == null) {
                mLoading = new LoadingBar(this);
            }
            mLoading.show();
            LedimApiServiceFactory.createService(ApiService.class)
                                  .userLogin(mAccountStr, mPasswordStr, LeDimApplication.getDeviceId(UserLoginActivity.this), "0", "0")
                                  .observeOn(AndroidSchedulers.mainThread())
                                  .subscribeOn(Schedulers.io())
                                  .subscribe(new LedimHttpObserver<LoginResponseBean>() {
                                     @Override
                                     public void onCompleted() {
                                         super.onCompleted();
                                     }

                                     @Override
                                     public void onError(Throwable e) {
                                         super.onError(e);
                                         mLoading.dismiss();
                                         ToastUtil.toast(e.getMessage());
                                     }

                                     @Override
                                     public void onNext(LoginResponseBean loginResponse) {
                                         super.onNext(loginResponse);
                                         mLoading.dismiss();
                                         if (loginResponse != null) {
                                             if (loginResponse.success) {
                                                 try {
                                                     //登录成功
                                                     ToastUtil.toast("登录成功");
                                                     LedimSpUtils.setUid(loginResponse.ext.userId);
                                                     LedimSpUtils.setToken(loginResponse.data.token);
                                                     LedimSpUtils.setLetvId(loginResponse.ext.letvid);
                                                     LedimSpUtils.setUser(LedimGsonConverterFactory.create().gson
                                                             .toJson(loginResponse.ext));
                                                     LedimSpUtils.setLogin(true);

                                                     //发送数据
                                                     if (loginResponse.ext != null &&
                                                             !TextUtils.isEmpty(loginResponse.ext.userId)) {
                                                         HashMap<String, String> params =
                                                                 new HashMap<String, String>();
                                                         params.put("uid", loginResponse.ext.userId);
                                                         params.put("loginfrom", "letv");
                                                         LeDimAnalysisUtils.reportEvent("login", params);
                                                     }
                                                     finish();

                                                 } catch (Exception e) {
                                                     e.printStackTrace();
                                                 }
                                             } else {
                                                 //登录失败
                                                 ToastUtil.toast(loginResponse.message);
                                             }
                                         }
                                     }
                                 });
        }
    }

    private void backForResult() {
        if (mBundle != null) {
            if (mBundle.getInt(ConstantUtil.REQUSET) == ConstantUtil.LOGIN_REQUEST) {
                if (LedimSpUtils.isLogin()) {
                    setResult(ConstantUtil.LOGIN_SUCCESS_RESPONSE);
                } else {
                    setResult(ConstantUtil.LOGIN_CANCEL_RESPONSE);
                }
            }
        }
    }

    @Override
    public void finish() {
        backForResult();
        super.finish();
        if (mNeedLogin) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(Message event) {
        Message message = event;
        if (message.what == ConstantUtil.EventBusMsgConstant.WEIXIN_LOGIN) {
            //实现微信请求
            mOtherLoginView.event((String) message.obj);
        }
    }

    //触摸屏幕关闭键盘
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        closeKeyBoard();
        return false;
    }

    /**
     * 关闭键盘
     */
    public void closeKeyBoard() {
        mAccount.clearFocus();
        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mAccount.getWindowToken(), 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoading != null) {
            mLoading.dismiss();
        }
    }

}
